package com.boarsoft.boar.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.websocket.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.app.AppBiz;
import com.boarsoft.boar.app.AppInstBiz;
import com.boarsoft.boar.entity.AppInfo;
import com.boarsoft.boar.entity.AppInst;
import com.boarsoft.rpc.bean.RpcRegistry;
import com.boarsoft.rpc.listener.RpcListener;
import com.boarsoft.web.websocket.WebsocketEndpoint;
import com.boarsoft.web.websocket.WebsocketMessage;

@Component("appInstService")
public class AppInstServiceImpl implements AppInstService, RpcListener {
	private static final Logger log = LoggerFactory.getLogger(AppInstServiceImpl.class);

	@Autowired
	protected AppInstBiz appInstBiz;
	@Autowired
	protected AppBiz appBiz;

	@Override
	public Integer getInstNo(String ip, int port) {
		AppInst o = appInstBiz.find(ip, port);
		return o.getNo();
	}

	@Override
	public List<AppInst> list(String appId, String env, String group, Short status) {
		return appInstBiz.list(env, appId, group, status);
	}

	@Override
	public void delete(String addr) {
		String[] a = addr.split(":");
		AppInst o = appInstBiz.find(a[0], Integer.parseInt(a[1]));
		appInstBiz.delete(o);
	}

	@Override
	public void onRemoveLink(String addr, String reason) {
		log.info("Rpc link {} be removed because {}", addr, reason);
		String[] a = addr.split(":");
		AppInst inst = appInstBiz.find(a[0], Integer.parseInt(a[1]));
		if (inst == null) {
			log.warn("Info of app instance {} not found", addr);
			return;
		}
		AppInfo app = appBiz.get(inst.getAppId());
		appInstBiz.status(inst.getId(), AppInst.STATUS_STOPPED);
		//
		Map<String, Object> rm = new HashMap<String, Object>();
		rm.put("addr", addr);
		rm.put("appCode", app.getCode());
		rm.put("instId", inst.getId());
		rm.put("status", AppInst.STATUS_STOPPED);
		//
		WebsocketMessage mw = new WebsocketMessage();
		mw.setGroup("app");
		mw.setCode("inst");
		mw.setData(rm);
		//
		Map<String, Session> sm = WebsocketEndpoint.getSessionMap();
		for (String wssid : sm.keySet()) {
			WebsocketEndpoint.send(mw, wssid);
		}
	}

	@Override
	public void onRegister(RpcRegistry reg) {
		// Nothing to do
	}

	@Override
	public void onDeregister(RpcRegistry reg) {
		// Nothing to do
	}

	@Override
	public void onUpdateRegistry(RpcRegistry rr) {
		// Nothing to do
	}

	@Override
	public boolean status(String id, short status) {
		return appInstBiz.status(id, status);
	}
}